//
//  IMB_NetFileUploadHelper.m
//  BabyNow
//
//  Created by 闫建刚 on 14-7-26.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "IMB_NetFileUploadHelper.h"
#import "IMB_UploadProgress.h"
#import <ASIHTTPRequest/ASIFormDataRequest.h>

@interface IMB_NetFileUploadHelper()<ASIHTTPRequestDelegate>
{
    /**
     *  上传进度
     */
    IMB_UploadProgress *upProgress_;
    
    /**
     *  请求对象
     */
    ASIFormDataRequest *request_;
    
    /**
     *  处理完毕回调
     */
    DataHandleComplete completeHandler_;
}
@end

@implementation IMB_NetFileUploadHelper

- (void)dealloc{
    [self cancleUpload];
    NSLog(@"IMB_NetFileUploadHelper dealloc ....");
}

- (id)initWithUrlStr:(NSString *)url
commonFormParamsDict:(NSDictionary *)commonFormParamsDict
         fileInfoArr:(NSArray *)fileInfoArr
     completeHandler:(DataHandleComplete)completeHandler
uploadProcessingHandler:(UploadProcessingHandler)uploadProcessingHandler{
    if (self = [super init]) {
        // 创建请求对象
        request_ = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:url]];
        request_.requestMethod = @"POST";
        request_.delegate = self;
        // 设置普通表单数据
        for (NSString *key in commonFormParamsDict) {
            [request_ addPostValue:commonFormParamsDict[key] forKey:key];
        }
        // 设置文件表单
        NSData *fileData;
        for (NSDictionary *fileDict in fileInfoArr) {
            fileData = fileDict[kFileData];
            [request_ addData:fileDict[kFileData] withFileName:fileDict[kFileName] andContentType:kFileMimeType forKey:fileDict[kFileUploadName]];
        }
        // 设置上传进度代理
        upProgress_ = [[IMB_UploadProgress alloc]initWithUploadProgressHandler:uploadProcessingHandler];
        [request_ setUploadProgressDelegate:upProgress_];
        
        completeHandler_ = completeHandler;
        
        [request_ startAsynchronous];
    }
    return self;
} // 初始化方法

- (void)cancleUpload{
    [request_ cancel];
    [request_ clearDelegatesAndCancel];
    request_ = nil;
}

#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request{
    NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableLeaves error:&err];
    NSLog(@"%@",resultDict);
    if (err) {
        completeHandler_(nil,NET_ERROR_MSG_FOR_RESPONSE_JSON_DATA);
    }else{
        completeHandler_(resultDict,nil);
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"%@",[request_.error localizedDescription]);
    completeHandler_(nil,[request_.error localizedDescription]);
}

@end
